<template>
	<view>
		<view class="top_flex flex_jc_sb">
			<view class="imgs flex">
				<image src="/static/shop1.png" mode=""></image>
				<view class="t1">可兑换稻穗值</view>
				<text>{{num}}</text>
			</view>
			<view class="imgs flex" @click="$pageGo('/mypage/more/order')">
				<image src="/static/shop2.png" mode=""></image>
				<view class="t1">文创订单</view>
			</view>
		</view>
		<view class="tab">
			<scroll-view class="tab_scroll" scroll-x scroll-with-animation :scroll-into-view="tabbar.intoIndex">
				<view class="tab_flex">
					<view
						:id="`item${index}`"
						class="items"
						:class="index == tabbar.active ? 'actitems' : ''"
						v-for="(item, index) in tabbar.tabbarList"
						:key="index"
						@click="tabbarChange(item,index)"
					>
						{{ item.name }}
					</view>
				</view>
			</scroll-view>
		</view>
		<loadstatusVue :status="data.loadStatus">
			<view class="content">
				<view class="item" v-for="(item,index) in data.list" :key="index" @click="$pageGo(`/mypage/more/shopdetail?id=${item.id}`)">
					<view class="item_top">
						<image :src="item.cover" mode="aspectFill"></image>
						<view class="tip">库存  {{item.count}}</view>
					</view>
					<view class="item_bottom">
						<view class="tit">{{item.name}}</view>
						<view class="price">
							<text>{{item.points}}</text>
							稻穗值 
							<span v-if="item.price!=0">
								+
								<text>{{item.price}}</text>
								{{item.priceType == 1?'元':'快递费'}}
							</span>
						</view>
					</view>
				</view>
			</view>
		</loadstatusVue>
	</view>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import loadstatusVue from '@/components/loadstatus/loadstatus.vue';
import { productAll, productList } from '@/api/shop.js';
import { toast, showConfirm } from '@/utils/common.js';
import { getConfig } from '@/api/login.js';
import { getData } from '@/api/user.js';
const tabbar = reactive({
	tabbarList: [],
	active: 0,
	intoIndex: ''
});
const data = reactive({
	list: [],
	loadStatus: 'before', // 加载状态
	hasMore: true, // 是否有更多数据
	isLoading: false, // 防止重复请求的锁
	queryParams: {
		type: '',
		pageNum: 1,
		pageSize: 10
	}
});
const tabbarChange = (item,index) => {
	data.queryParams.type = item.name
	if(item.name == '全部'){
		data.queryParams.type = ''
	}
	tabbar.intoIndex = 'item' + index;
	data.queryParams.pageNum = 1; // 重置页码
	tabbar.active = index;
	getList()
};
// 延迟函数
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// 设置加载状态的方法
const setLoadStatus = (status, options = {}) => {
	data.loadStatus = status;
};
// 处理响应数据的通用方法
const handleResponseData = async (res, isLoadMore = false) => {
	// 如果是加载更多，确保loading状态至少显示500ms，避免闪烁
	if (isLoadMore) {
		await delay(500);
	}
	if (res.code == 200) {
		// 处理数据
		if (isLoadMore) {
			data.list.push(...res.rows);
		} else {
			data.list = res.rows || [];
		}
		// 判断是否有更多数据
		data.hasMore = res.rows && res.rows.length >= data.queryParams.pageSize;
		// 设置状态
		if (data.list.length === 0) {
			setLoadStatus('empty');
		} else if (!data.hasMore) {
			setLoadStatus('noMore');
		} else {
			setLoadStatus('success');
		}
		return true;
	}
	return false;
};
// 获取列表数据
const getList = async (isLoadMore = false) => {
	// 防止重复请求
	if (data.isLoading) return;
	try {
		data.isLoading = true;
		if (isLoadMore) {
			if (!data.hasMore) return;
			setLoadStatus('loading');
		} else {
			setLoadStatus('before');
			// 初始加载时显示loading至少1秒，避免闪烁
			await delay(300);
		}
		const res = await productList(data.queryParams);
		const success = await handleResponseData(res, isLoadMore);
		if (!success) {
			// 请求失败的处理
			setLoadStatus(data.list.length === 0 ? 'empty' : 'success');
		}
	} catch (err) {
		await delay(300);
		setLoadStatus(data.list.length === 0 ? 'empty' : 'success');
	} finally {
		data.isLoading = false;
	}
};
const points = ref(0);
const num = ref(0);
const loadMore = () => {
  if (data.isLoading || !data.hasMore) {
    return false;
  }
  
  data.queryParams.pageNum++;
  getList(true); // 传递 true 表示是加载更多
  
  return true;
};
defineExpose({
	loadMore
});
onMounted(() => {
	uni.$on('changeShop',function(){
		getData({}).then((res) => {
			if (res.code == 200) {
				points.value = res.data.points
				getConfig({}).then((res) => {
					if (res.code == 200) {
						num.value = Math.max(points.value - res.data.mallNotUseUserPoints, 0);
					}
				});
			}
		});
		getList()
	})
	getData({}).then((res) => {
		if (res.code == 200) {
			points.value = res.data.points
			getConfig({}).then((res) => {
				if (res.code == 200) {
					num.value = Math.max(points.value - res.data.mallNotUseUserPoints, 0);
				}
			});
		}
	});
	productAll({}).then((res) => {
		if (res.code == 200) {
			tabbar.tabbarList = res.data;
			tabbar.tabbarList.unshift({name:'全部'})
			getList()
		}
	});
});
</script>
<style lang="scss" scoped>
.top_flex {
	width: 710rpx;
	margin: 0rpx auto;
	.imgs {
		width: 320rpx;
		height: 80rpx;
		background: #eee8d8;
		border-radius: 20rpx;
		padding: 0rpx 18rpx;
		box-sizing: border-box;
		image {
			width: 52rpx;
			height: 52rpx;
		}
		.t1 {
			font-family: PingFang SC, PingFang SC;
			font-weight: 500;
			font-size: 24rpx;
			color: #75613e;
			margin-left: 14rpx;
		}
		text {
			margin-left: 14rpx;
			font-family: 'DIN-BOLD';
			font-weight: 500;
			font-size: 32rpx;
			color: #75613e;
		}
	}
}
.tab {
	width: 750rpx;
	height: 72rpx;
	background: #f3f0e8;
	position: sticky;
	z-index: 4;
	top: 70rpx;
	overflow: hidden; /* 限制滚动范围 */
	.tab_scroll {
		width: 100%;
		height: 100%;
		white-space: nowrap; /* 防止内部元素换行 */
		// 隐藏横向滚动条（可选）
		&::-webkit-scrollbar {
			display: none;
		}
		scrollbar-width: none;
	}

	.tab_flex {
		display: inline-flex; // 让容器宽度随内容撑开
		height: 100%;
		align-items: center;
		padding: 0 10rpx; // 左右留一点边距
	}

	.items {
		min-width: 120rpx; // 每个选项最小宽度
		padding: 0 20rpx 0rpx 0rpx;
		height: 100%;
		line-height: 72rpx; // 垂直居中
		font-family: PingFang SC, PingFang SC;
		font-weight: 500;
		font-size: 24rpx;
		color: #717171;
		text-align: center;
		white-space: nowrap; // 文字不换行
	}
	.actitems {
		font-weight: bold;
		color: #75613e;
	}
}
.content {
	width: 710rpx;
	margin: 0rpx auto;
	display: flex;
	flex-wrap: wrap;
	justify-content: space-between;
	.item {
		width: 344rpx;
		height: 460rpx;
		background: #ffffff;
		border-radius: 20rpx;
		margin-bottom: 20rpx;
		.item_top {
			width: 344rpx;
			height: 300rpx;
			position: relative;
			image {
				width: 344rpx;
				height: 300rpx;
				border-radius: 20rpx 20rpx 0rpx 0rpx;
			}
			.tip {
				position: absolute;
				width: 100rpx;
				height: 50rpx;
				border-radius: 20rpx 0rpx 20rpx 0rpx;
				background: #b19561;
				top: 0%;
				left: 0%;
				font-family: PingFang SC, PingFang SC;
				font-weight: 500;
				font-size: 20rpx;
				color: #ffffff;
				text-align: center;
				line-height: 50rpx;
			}
		}
		.item_bottom {
			height: 160rpx;
			padding: 16rpx 20rpx;
			box-sizing: border-box;
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			.tit {
				font-family: PingFang SC, PingFang SC;
				font-weight: 500;
				font-size: 30rpx;
				color: #1b1b1b;
				overflow: hidden;
				text-overflow: ellipsis;
				display: -webkit-box;
				-webkit-line-clamp: 2; //几行就填几
				-webkit-box-orient: vertical;
			}
			.price {
				font-family: PingFang SC, PingFang SC;
				font-weight: 500;
				font-size: 20rpx;
				color: #75613e;
				margin-top: 6rpx;
				text-align: justified;
				text {
					font-family: 'DIN-BOLD';
					font-weight: 500;
					font-size: 32rpx;
					color: #892b1b;
					margin-right: 6rpx;
				}
			}
		}
	}
}
</style>
